package com.xindaoapp.henghua.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.util.EnergyError;
import com.loopj.android.http.util.RequestQueue;
import com.loopj.android.http.util.Response.ErrorListener;
import com.loopj.android.http.util.Response.Listener;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.UserInfo;
import com.xindaoapp.henghua.utils.MoccaPreferences;

/** 启动页 */
public class EnterDevicd extends Activity {

	private static final String SDCardPath = Environment.getExternalStorageDirectory().getPath();
	private static final String AppPath = "/henghua/";
	private static final String SAVE_PATH = SDCardPath + AppPath;

	public static final String GIIPVERSION = "3.0";
	private EditText etText;
	private View btn_sure;
	private final String deviceId = "";

	private String uuid = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_enter_device);

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
		((ImageView) findViewById(R.id.icon)).setBackgroundDrawable(new BitmapDrawable(getResources(),
				BitmapFactory.decodeResource(getResources(), R.drawable.bg_enter_device, options)));

		etText = (EditText) findViewById(R.id.et_device);

		createPath(SAVE_PATH);
		uuid = readData();
		if (!TextUtils.isEmpty(uuid)) {
			etText.setText(uuid);
		}

		btn_sure = findViewById(R.id.btn_sure);
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!TextUtils.isEmpty(uuid)) {
					if (!TextUtils.isEmpty(etText.getText().toString())) {

						if (MoccaPreferences.FIRSTlOGIN.get().equals("0")) {
							login();
						} else if (etText.getText().toString().equals(uuid)) {

							RequestQueue.client.addHeader("giipVersion", GIIPVERSION);
							RequestQueue.client.addHeader("udid", uuid);
							RequestQueue.client.addHeader("appVersion", getVersionName());
							RequestQueue.client.addHeader("appName", getPackageName());

							try {
								XinDaoApplication.get().setUserInfo(
										JSON.parseObject(new JSONObject(MoccaPreferences.UERERINFO.get())
												.getJSONObject("content").toString(), UserInfo.class));
							} catch (JSONException e) {
								e.printStackTrace();
							}

							Intent intent = new Intent(getBaseContext(), DeviceEngineerActivity.class);
							startActivity(intent);
							finish();
						} else {
							showDialog(EnterDevicd.this);
						}
					} else {
						Toast.makeText(EnterDevicd.this, "ID不能为空！", Toast.LENGTH_SHORT).show();
					}

				} else {
					login();
				}
			}
		});

	}

	private void login() {
		final String deviceId = etText.getText().toString();

		if (TextUtils.isEmpty(deviceId)) {
			Toast.makeText(EnterDevicd.this, "ID不能为空！", Toast.LENGTH_SHORT).show();
		} else {
			showDialog(DIALOG_LOGIN);
			XinDaoApplication
					.get()
					.getMoccaApi()
					.login(getPackageName(), getVersionName(), GIIPVERSION, deviceId,
							new Listener<UserInfo>() {

								@Override
								public void onResponse(UserInfo response) {
									removeDialog(DIALOG_LOGIN);
									// 跳转主页
									if (null != response && !TextUtils.isEmpty(response.project_id)) {
										MoccaPreferences.DeviceId.put(deviceId);
										writeData(deviceId);
										XinDaoApplication.get().getDBHelper().clearAllTable();
										XinDaoApplication.get().setUserInfo(response);

										if (MoccaPreferences.FIRSTlOGIN.get().equals("0")) {
											MoccaPreferences.FIRSTlOGIN.put("1");
										}

										Intent intent = new Intent(getBaseContext(),
												DeviceEngineerActivity.class);
										startActivity(intent);
										finish();
									} else {
										Toast.makeText(getBaseContext(), "登录失败", Toast.LENGTH_SHORT).show();
									}
								}
							}, new ErrorListener() {

								@Override
								public void onErrorResponse(EnergyError error) {
									removeDialog(DIALOG_LOGIN);
									Toast.makeText(getBaseContext(), "登录失败，请检查网络", Toast.LENGTH_SHORT).show();
								}
							});
		}

	}

	// 显示基本的AlertDialog
	private void showDialog(final Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("更改设备号会重置数据，请慎重操作");
		builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				login();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {

			}
		});
		builder.show();
	}

	@SuppressWarnings("deprecation")
	private void writeData(String content) {
		FileOutputStream fos = null;
		String filename = "henghua.txt";

		File file = new File(SAVE_PATH + filename);

		if (isHaveSDCard()) {
			try {
				fos = new FileOutputStream(file);
				fos.write(content.getBytes());
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			Toast.makeText(EnterDevicd.this, "SD卡不存在！", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 创建目录
	 */
	public static File createPath(String path) {

		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

		return file;

	}

	private String readData() {
		String name = "henghua.txt";
		String filename = SAVE_PATH + name;
		FileInputStream fis;
		String str = null;
		try {
			fis = new FileInputStream(filename);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			try {
				while ((length = fis.read(buffer)) != -1) {
					bos.write(buffer, 0, length);
				}
				fis.close();
				bos.close();
				bos.toByteArray();
				str = new String(bos.toByteArray());
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return str != null ? str : "";
	}

	private boolean isHaveSDCard() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	private String getVersionName() {
		try {
			return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return "";
	}

	protected static final int DIALOG_LOADING = 1;// 数据加载
	protected static final int DIALOG_LOGIN = 2;// 登录
	protected static final int DIALOG_SUBMIT = 3;// 提交

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		ProgressDialog pd = new ProgressDialog(this);
		switch (id) {
		case DIALOG_LOADING:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_data));
			pd.setCancelable(false);
			return pd;
		case DIALOG_LOGIN:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_login));
			pd.setCancelable(false);
			return pd;
		case DIALOG_SUBMIT:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_data));
			pd.setCancelable(false);
			return pd;
		}
		return null;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		BitmapDrawable drawable = (BitmapDrawable) ((ImageView) findViewById(R.id.icon)).getBackground();
		Bitmap bmp = drawable.getBitmap();
		if (null != bmp && !bmp.isRecycled()) {
			bmp.recycle();
			bmp = null;
		}
	}

}
